<?php
/**
 * @author Martin Scotta <martinscotta@gmail.com>
 */

/**
 * ClassLoader 
 */
final class LiteClassLoader implements Lite_Loader_AutoLoader {
	
	/**
	 * @var ClassLoader
	 */
	private static $instance;
	
	 /**
	 * Obtener la instancia del ClassLoader
	 * 
	 * @return Lite_Loader_AutoLoader
	 */
	static function getInstance() {
		if( null === self::$instance ) {
			self::$instance = new self;
		}
		return self::$instance;
	}

	/**
	 * @param Lite_Loader_AutoLoader $loader
	 */
	static function registerAutoloader(Lite_Loader_AutoLoader $loader=null){
		$instance = self::getInstance();
		
		if( null !== $loader ) {
			$instance->register( $loader );
		}
	}
	
	/**
	 * @var array Vector de loaders registrados
	 */
	private $loaders = array();
  
	/**
	 */
	private function __construct() {
		spl_autoload_register(
			array( $this, 'autoload' )
		);
	}
	
	/**
	 * Agrega un loader
	 * 
	 * @param Lite_Loader_AutoLoader $loader
	 */
	function register(Lite_Loader_AutoLoader $loader) {
		if(!in_array($loader, $this->loaders)){
			$this->loaders[] = $loader;
		} 
	}

	/**
	 * Envia el pedido a los loaders registrados
	 * 
	 * @param string $name nombre de la clase o interfaz a cargar
	 * @return boolean
	 */
	function autoload($name) {
		if( class_exists($name, false))
			return true;
		
		foreach($this->loaders as $loader) {
			if( $loader->autoload($name)) {
				return true;
			}
		}
		return false;
	}
}
